package get

import (
	"encoding/base64"
	"errors"
	"fmt"
	"gitee.com/hubdev/api/pkg/meta"
	"gitee.com/pkg/root"
	"gitee.com/runx/gitctl/pkg/api/conf"
	"gitee.com/runx/gitctl/pkg/api/tab"
	v1 "gitee.com/runx/gitctl/pkg/api/v1"
	"gitee.com/runx/gitctl/pkg/cli"
	getv1 "gitee.com/runx/gitctl/pkg/cli/get"
	"gitee.com/runx/gitctl/pkg/cli/ops"
	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"
	"strings"
)

var (
	ns     string
	out    string
	xConf  string
	xCli   *cli.Cli
	getCmd = &cobra.Command{
		Use:   "get",
		Short: "get resources",
		RunE: func(c *cobra.Command, args []string) error {
			if len(args) == 0 {
				return errors.New("you need set name args")
			}
			var err error
			kind := strings.TrimSuffix(args[0], "s")
			resName := ""
			if len(args) > 1 {
				resName = args[1]
			}
			res := &v1.Resource{
				Kind: kind,
				Metadata: &meta.Metadata{
					Name:      resName,
					Namespace: ns,
				},
			}
			ctx := xCli.NewCtx(ops.GetFile, res)
			//resname is null,show all of namespace
			if resName == "" {
				rsps := make([]*getv1.Content, 0)
				err = ctx.Invoke(&rsps)
				clos := []string{"name", "path", "sha"}
				if tb, err := tab.Of(clos); err == nil {
					for _, rsp := range rsps {
						tb.AddRow(map[string]string{
							"name": strings.TrimSuffix(rsp.Name,".yaml"),
							"path": strings.TrimPrefix(rsp.Path, fmt.Sprintf("%ss", kind)),
							"sha":  rsp.Sha,
						})
					}
					tb.Print()
				}
				return nil
			}
			rsp := &getv1.Content{}
			if err = ctx.Invoke(rsp); err != nil {
				return err
			}
			if out == "yaml" {
				ct, err := base64.StdEncoding.DecodeString(rsp.Content)
				if err != nil {
					fmt.Println("out error:%v", err)
				} else {
					fmt.Println(string(ct))
				}
			} else {
				clos := []string{"name", "path", "sha"}
				if tb, err := tab.Of(clos); err == nil {
					tb.AddRow(map[string]string{
						"name": res.Metadata.Name,
						"path": strings.TrimPrefix(rsp.Path, "inputs/"),
						"sha":  rsp.Sha,
					})
					tb.Print()
				}
			}
			return nil
		},
	}
)

func init() {
	homer, _ := conf.Home()

	getCmd.PersistentFlags().StringVarP(&ns, "namespace", "n", "default", "set resource namespace")
	getCmd.PersistentFlags().StringVarP(&out, "out", "o", "table", "set out format")
	getCmd.PersistentFlags().StringVarP(&xConf, "config", "c", homer+"/.gitops/config", "tool config file ")
	config := &conf.Config{}
	err := yaml.Unmarshal(conf.GetData(xConf), config)
	if err != nil {
		panic(err)
	}
	xCli = cli.New(config)
	root.AddCmd(getCmd)
}
